<?php


namespace App\Services;

use App\Models\Warranty;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use \Exception;

class WarrantyDeleteService
{
    public function add(Request $request)
    {
        $warranty = Warranty::where('warranty_id', $request->input('warranty_id'))->first();
        if (empty($warranty)) {
            throw new \Exception('该质保数据不存在');
        }

        if ($warranty->distributor_id != session('admin.id')) {
            throw new Exception('该账号无权限操作');
        }

        if (!empty($warranty->deleted_at)) {
            throw new Exception('该质保数据已删除');
        }

        if ($warranty->approved != 1) {
            throw new Exception('该质保数据状态错误');
        }

        $deleteWarranty = DB::table('warranty_delete')->where('warranty_id', $request->input('warranty_id'))->first();
        if ($deleteWarranty) {
            throw new Exception('该质保ID已提交');
        }


        DB::table('warranty_delete')->insert(
            [
                'warranty_id' => $request->input('warranty_id'),
                'user_id'     => session('admin.id'),
                'delete_reason' => trim($request->input('reason')),
                'created_time'  => date('Y-m-d H:i:s')
            ]
        );
    }

    public function getList(Request $request)
    {
        $model = DB::table('warranty_delete')
            ->leftJoin('users', 'warranty_delete.user_id', 'users.id')
            ->whereNull('warranty_delete.deleted_at');

        if (session('admin.user_type') == 2) {
            $model = $model->where('user_id', session('admin.id'));
        }

        if (!empty($request->input('value'))) {
            $model = $model->where('warranty_id', $request->input('value'));
        }

        if (!empty($request->input('distribution_id'))) {
            $model = $model->where('user_id', $request->input('distribution_id'));
        }

        if (!empty($request->input('startdate'))) {
            $model = $model->where('created_time', '>=', $request->input('startdate'));
        }

        if (!empty($request->input('enddate'))) {
            $model = $model->where('created_time', '<=', date('Y-m-d', strtotime($request->input('enddate')) + 86400));
        }

        return $model->select('warranty_delete.*', 'users.abbr', 'users.unique_id')
            ->orderByDesc('id')
            ->paginate(50);
    }

    public function delete(int $id)
    {
        $warranty = DB::table('warranty_delete')->where('id', $id);
        if (empty($warranty)) {
            throw new Exception('数据不存在');
        }
        if (!empty($warranty->deleted_at)) {
            throw new Exception('数据已删除');
        }

        return DB::table('warranty_delete')->where('id', $id)->update(['deleted_at' => date('Y-m-d H:i:s')]);
    }
}